package com.czumi.javawx.web.controller.admin;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.czumi.javawx.constants.UrlConst;
import com.czumi.javawx.constants.WeixinConst;
import com.czumi.javawx.dao.entity.WeixinFan;
import com.czumi.javawx.dao.entity.WeixinGroup;
import com.czumi.javawx.service.WeixinFanService;
import com.czumi.javawx.service.WeixinGroupService;
import com.czumi.javawx.util.EneityUtil;
import com.czumi.javawx.web.controller.weixin.WeixinController;
import com.czumi.javawx.web.form.ResultDto;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.GetUsersResponse;
import com.github.sd4324530.fastweixin.api.response.GetUsersResponse.Openid;

/**
 * 创建时间：2017年10月27日 下午9:55:35 项目名称：javawx
 * 
 * @author 袁友林 文件名称：WeiXinFanController.java 类说明： 微信粉丝处理
 */
@Controller
public class WeiXinFanController{

	@Autowired
	private WeixinFanService weixinFanService;

	@Autowired
	private WeixinGroupService weixinGroupService;

	@RequestMapping(value = UrlConst.URL_ADMIN_WEIXIN_FAN_GRID, method = RequestMethod.GET)
	public String grid(ModelMap model) {
		List<WeixinFan> list = weixinFanService.getAllWeixinFans();
		model.addAttribute("list", list);

		List<WeixinGroup> groups = weixinGroupService.getAllWeixinGroup();
		groups.add(new WeixinGroup(0, "游客"));
		model.addAttribute("groups", groups);

		return UrlConst.WEB_ADMIN_WEIXIN_FAN_GRID;
	}

	@RequestMapping(value = UrlConst.URL_ADMIN_UPDATE_WEIXIN_FAN_GROUP, method = RequestMethod.POST)
	public ResultDto update(WeixinFan weixinFan) {
		ResultDto resultDto = new ResultDto();
		resultDto.setFlag(1);
		return resultDto;
	}
	
	@RequestMapping(value = UrlConst.URL_ADMIN_WEIXIN_FAN_SYNC, method = RequestMethod.POST)
	@ResponseBody
	public ResultDto syncFans() {
		ResultDto resultDto=new ResultDto();
		UserAPI userAPI = new UserAPI(WeixinConst.apiConfig);
		GetUsersResponse users =userAPI.getUsers("");	
		List<WeixinFan> list=new ArrayList<>();
		if(users.getCount()>0) {
			for (int i = 0; i < users.getCount(); i++) {
				GetUserInfoResponse userinfo = userAPI.getUserInfo(users.getData().getOpenid()[i]);
				list.add(EneityUtil.convertWeixinFan(userinfo));
			}
			weixinFanService.saveAndUpdate(list);
		}
		resultDto.setFlag(1);
		return resultDto;
	}

}
